<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    /**
     * 数据结构 栈的练习 
     **/
  // 计算右边比我小的元素的位置
  const findRightSmall = (list) =>{
    const stack = []
    const result = []
    list.forEach((el, i) => {
      // 消除栈
      while(stack.length  && el < list[stack[stack.length - 1]]) {
        result[stack[stack.length - 1]] = i
        stack.pop()
      }
      stack.push(i)
    });
    while(stack.length) {
      result[stack[stack.length - 1]] = -1
      stack.pop()
    }
    console.log(result)
    return result
  }
  findRightSmall([1,2,4,9,4,0, 5]) // 4 5 5 5 5 -1 -1 
  findRightSmall([5, 2]) // 4 5 5 5 5 -1 -1 

  // 变形题: 数组中元素左边离我最近且比我大的元素的位置
  const findLeftMax = (list) => {
    const stack = []
    const result = []
    list.forEach((el, i) => {
      debugger
      // 消除栈
      while(stack.length  && el < list[stack[stack.length - 1]]) {
        result[i] = stack[stack.length - 1] // result[1] = 0
        stack.pop()
      }
      stack.push(i) // stack[1]
    });
    while(stack.length) {
      result[stack[stack.length - 1]] = -1
      stack.pop()
    }
    console.log(result)
    return result
  }
  // findLeftMax([1,2,4,9,4,0, 5]) // 4 5 5 5 5 -1 -1 
  findLeftMax([5, 2]) // 4 5 5 5 5 -1 -1 
  </script>
</body>

</html>